#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
流水线使用示例
演示如何使用分步流水线生成视频
"""

from pathlib import Path
import logging

from generate_video.pipeline import Pipeline
from generate_video.pipeline.steps import (
    ParseMarkdownStep,
    GenerateScenesStep,
    SynthesizeTTSStep,
    GenerateAnimationsStep,
    RenderVideoStep,
)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def create_sample_markdown():
    """创建示例Markdown文件"""
    content = """# 机器学习入门

## 什么是机器学习？

机器学习是人工智能的一个分支，它使计算机能够在没有明确编程的情况下学习。

### 核心概念

- **监督学习**: 使用标记数据训练模型
- **无监督学习**: 从未标记数据中发现模式
- **强化学习**: 通过试错学习最优策略

## 简单代码示例

```python
import numpy as np
from sklearn.linear_model import LinearRegression

# 创建模型
model = LinearRegression()

# 训练模型
model.fit(X_train, y_train)

# 预测
predictions = model.predict(X_test)
```

## 数学公式

机器学习中的损失函数：

$$L(\theta) = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2$$
"""

    markdown_file = Path("examples/sample_input.md")
    markdown_file.parent.mkdir(exist_ok=True)

    with open(markdown_file, "w", encoding="utf-8") as f:
        f.write(content)

    return markdown_file


def demo_pipeline():
    """演示流水线使用"""
    print("=" * 60)
    print("视频生成流水线演示")
    print("=" * 60)

    # 创建示例Markdown文件
    markdown_file = create_sample_markdown()
    print(f"\n✓ 创建示例文件: {markdown_file}")

    # 设置输出目录
    output_dir = Path("examples/output")
    output_dir.mkdir(parents=True, exist_ok=True)

    # 创建步骤
    print("\n创建流水线步骤...")

    # 步骤1: 解析Markdown
    parse_step = ParseMarkdownStep(
        markdown_file=markdown_file,
        output_dir=output_dir / "01_parse",
    )
    print(f"  1. {parse_step.name}: {parse_step.description}")

    # 步骤2: 生成场景
    generate_step = GenerateScenesStep(
        output_dir=output_dir / "02_scenes",
        theme="dark",
    )
    print(f"  2. {generate_step.name}: {generate_step.description}")

    # 步骤3: TTS合成
    tts_step = SynthesizeTTSStep(
        output_dir=output_dir / "03_tts",
        voice_config={"voice": "zh-CN-XiaoxiaoNeural"},
        text_list=[
            "欢迎来到机器学习入门教程",
            "首先介绍什么是机器学习",
            "机器学习是人工智能的一个分支",
        ],
    )
    print(f"  3. {tts_step.name}: {tts_step.description}")

    # 步骤4: 生成动画
    anim_step = GenerateAnimationsStep(
        output_dir=output_dir / "04_animations",
        quality="standard",
    )
    print(f"  4. {anim_step.name}: {anim_step.description}")

    # 步骤5: 渲染视频
    render_step = RenderVideoStep(
        output_dir=output_dir / "05_render",
        output_settings={
            "format": "mp4",
            "quality": "standard",
            "resolution": "1920x1080",
        },
    )
    print(f"  5. {render_step.name}: {render_step.description}")

    # 创建流水线
    print("\n创建流水线...")
    pipeline = Pipeline(
        name="machine_learning_tutorial",
        steps=[parse_step, generate_step, tts_step, anim_step, render_step],
        checkpoint_dir=output_dir / "checkpoints",
        auto_save=True,
    )

    # 设置进度回调
    def progress_callback(percent: int, message: str):
        print(f"\r  进度: {percent:3d}% - {message}", end="", flush=True)

    pipeline.set_progress_callback(progress_callback)

    print("\n开始执行流水线...")
    print("-" * 60)

    # 运行流水线
    result = pipeline.run()

    print("\n" + "=" * 60)
    if result.success:
        print("✓ 流水线执行成功!")
        print(f"  {result.message}")
    else:
        print("✗ 流水线执行失败!")
        print(f"  {result.message}")
    print("=" * 60)

    return result


def demo_step_by_step():
    """演示分步执行"""
    print("\n" + "=" * 60)
    print("分步执行演示")
    print("=" * 60)

    # 创建示例Markdown文件
    markdown_file = create_sample_markdown()
    output_dir = Path("examples/output_step_by_step")
    output_dir.mkdir(parents=True, exist_ok=True)

    # 步骤1: 解析Markdown
    print("\n步骤1: 解析Markdown")
    parse_step = ParseMarkdownStep(
        markdown_file=markdown_file,
        output_dir=output_dir / "01_parse",
    )
    result = parse_step.execute()
    if not result.success:
        print(f"  ✗ 失败: {result.message}")
        return

    print(f"  ✓ 成功: {result.message}")

    # 步骤2: 生成场景
    print("\n步骤2: 生成场景")
    generate_step = GenerateScenesStep(
        output_dir=output_dir / "02_scenes",
        theme="academic",
    )
    result = generate_step.execute()
    if not result.success:
        print(f"  ✗ 失败: {result.message}")
        return

    print(f"  ✓ 成功: {result.message}")

    # 步骤3: TTS合成
    print("\n步骤3: TTS合成")
    tts_step = SynthesizeTTSStep(
        output_dir=output_dir / "03_tts",
        text_list=[
            "这是第二步演示",
            "展示了分步执行功能",
            "每个步骤可以独立执行",
        ],
    )
    result = tts_step.execute()
    if not result.success:
        print(f"  ✗ 失败: {result.message}")
        return

    print(f"  ✓ 成功: {result.message}")

    print("\n" + "=" * 60)
    print("✓ 分步执行完成!")
    print("=" * 60)


if __name__ == "__main__":
    # 运行完整流水线演示
    demo_pipeline()

    # 运行分步执行演示
    demo_step_by_step()

    print("\n演示完成!")
    print("请查看 examples/output 目录下的输出文件")
